package com.mingtang.online.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.mingtang.online.HideFragmentActivity;
import com.mingtang.online.MainActivity;
import com.mingtang.online.R;
import com.mingtang.online.adapter.IndexAdapter;
import com.mingtang.online.bean.ShangPin;
import com.mingtang.online.changliang.Const;
import com.mingtang.online.http.MyOkhttp;
import com.mingtang.online.http.callback.StringNoDialogCallback;
import com.mingtang.online.http.request.BaseRequest;
import com.mingtang.online.model.LoginModel;
import com.mingtang.online.util.Regular;
import com.mingtang.online.util.SharePreferenceUtil;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/10/16.
 */

public class LoginActivity extends BaseActivity {

    @BindView(R.id.img_return)
    ImageView imgReturn;
    @BindView(R.id.layout_return)
    LinearLayout layoutReturn;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.edit_password)
    EditText editPassword;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.text_register)
    TextView textRegister;
    @BindView(R.id.text_forget)
    TextView textForget;
    @BindView(R.id.img_xinlang)
    ImageView imgXinlang;
    @BindView(R.id.img_wx)
    ImageView imgWx;
    @BindView(R.id.img_qq)
    ImageView imgQq;
    private SHARE_MEDIA[] list = {SHARE_MEDIA.QQ, SHARE_MEDIA.SINA, SHARE_MEDIA.WEIXIN};
    String openid;
    String pic_url;
    String name;
    UMAuthListener authListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
//            SocializeUtils.safeShowDialog(dialog);
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
//            SocializeUtils.safeCloseDialog(dialog);
            String temp = "";
            for (String key : data.keySet()) {
                temp = temp + key + " : " + data.get(key) + "\n";
                Log.d(data.get(key), "ggggggggggggggggggggggg");
            }

            openid = data.get("openid");
            pic_url = data.get("iconurl");
            name = data.get("name");
//            getLogin2();

            Toast.makeText(LoginActivity.this, "完成登录", Toast.LENGTH_SHORT).show();
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
//            SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(LoginActivity.this, "失败：" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
//            SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(LoginActivity.this, "取消了", Toast.LENGTH_LONG).show();
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

    }

    public void getLogin() {

        MyOkhttp.post(Const.MODEL_URL)
                .tag(this)
                .params("i", "3")
                .params("c", "auth")
                .params("a", "applogin")
                .params("do", "basic")
                .params("username", editPhone.getText().toString())
                .params("password", editPassword.getText().toString())

                .execute(new StringNoDialogCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        showLoading();

                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");
                        LoginModel loginModel = new LoginModel();
                        Gson gson = new Gson();
                        loginModel = gson.fromJson(s, LoginModel.class);
                        if (loginModel.getStatus().equals("0")) {
                            SharePreferenceUtil.put(LoginActivity.this, "userid", loginModel.getUser().getUid());
                            EventBus.getDefault().post(4);
                            startActivity(new Intent(LoginActivity.this, HideFragmentActivity.class));
                            finish();
                        /*    EventBus.getDefault().post(1);
                            finish();*/
                        } else {
                            Toast.makeText(LoginActivity.this, "用户名或密码不正确请重试", Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        dismissLoading();
                    }

                    @Override
                    public void onAfter(String s, Exception e) {
                        super.onAfter(s, e);
                        dismissLoading();
                    }
                });
    }


    @OnClick({R.id.img_return, R.id.layout_return, R.id.edit_phone, R.id.edit_password, R.id.btn_login, R.id.text_register, R.id.text_forget, R.id.img_xinlang, R.id.img_wx, R.id.img_qq})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_return:
//                EventBus.getDefault().post(4);
//                finish();
//Intent intent=new Intent();
                startActivity(new Intent(LoginActivity.this, HideFragmentActivity.class));
                finish();
                break;

            case R.id.layout_return:
//                EventBus.getDefault().post(4);
                startActivity(new Intent(LoginActivity.this, HideFragmentActivity.class));
                finish();
                break;
            case R.id.edit_phone:
                break;
            case R.id.edit_password:
                break;
            case R.id.btn_login:
//                Toast.makeText(this, "跳转到登录", Toast.LENGTH_SHORT).show();
                if (TextUtils.isEmpty(editPhone.getText().toString())) {
                    Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(editPassword.getText().toString())) {
                    Toast.makeText(this, "用户密码不能为空", Toast.LENGTH_SHORT).show();
                } else if (!Regular.isMobileNO(editPhone.getText().toString())) {

                    Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();

                } else {
                    getLogin();
                }


                break;
            case R.id.text_register:
                Toast.makeText(this, "跳转到注册", Toast.LENGTH_SHORT).show();
                break;
            case R.id.text_forget:
                Toast.makeText(this, "跳转到忘记密码", Toast.LENGTH_SHORT).show();
                break;
            case R.id.img_xinlang:
                Toast.makeText(this, "跳转到新浪", Toast.LENGTH_SHORT).show();
                break;
            case R.id.img_wx:
                Toast.makeText(this, "跳转到微信", Toast.LENGTH_SHORT).show();
                UMShareConfig config = new UMShareConfig();
                config.isNeedAuthOnGetUserInfo(true);
                UMShareAPI.get(LoginActivity.this).setShareConfig(config);
//               UMShareAPI.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
//               UMShareAPI.get(LoginActivity.this).doOauthVerify(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
                UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, authListener);

                break;
            case R.id.img_qq:
                Toast.makeText(this, "跳转到qq", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);//完成回调


    }

    private long clickTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if ((System.currentTimeMillis() - clickTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再次点击退出", Toast.LENGTH_SHORT).show();
            clickTime = System.currentTimeMillis();
        } else {
//            Log.e(TAG, "exit application");
            this.finish();
            System.exit(0);
        }
    }

}
